//给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。 
//
// 
//
// 示例 1： 
// 
// 
//输入：head = [1,2,3,4,5], k = 2
//输出：[4,5,1,2,3]
// 
//
// 示例 2： 
// 
// 
//输入：head = [0,1,2], k = 4
//输出：[2,0,1]
// 
//
// 
//
// 提示： 
//
// 
// 链表中节点的数目在范围 [0, 500] 内 
// -100 <= Node.val <= 100 
// 0 <= k <= 2 * 10⁹ 
// 
//
// Related Topics 链表 双指针 👍 1038 👎 0


package LeetCode.editor.cn;

/**
 * @author ldltd
 * @date 2024-03-26 00:11:14
 * @description 61.旋转链表
 */
public class RotateList {
    public static void main(String[] args) {
        //测试代码
        RotateList fun = new RotateList();
        Solution solution = fun.new Solution();
        ListNode head = fun.new ListNode(1);
//        head.next = fun.new ListNode(2);
//        head.next.next = fun.new ListNode(3);
        solution.rotateRight(head,1);
    }

//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)

    //Definition for singly-linked list.
    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
    class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if(head==null||k==0) return head;
            int t = 0;
            ListNode res = new ListNode(0, head);
            ListNode p = head;
            //计算总的节点数
            while (head != null) {
                head = head.next;
                t++;
            }
            head = p;
            //计算真的右移数量
            if(k%t==0)
                return head;
            k = k % t;
            ListNode fast = head;
            ListNode slow = head;
            //
            while (k-- > 0) {
                fast = fast.next;
            }
            while (fast.next != null) {
                fast = fast.next;
                slow = slow.next;
            }
            ListNode next = slow.next;
            res.next=next;
            slow.next=null;
            fast.next=head;
            return res.next;

        }


    }
//leetcode submit region end(Prohibit modification and deletion)

}
